package dbms;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;

public class DBGeneralFunctions {

	public static HashMap<Integer, String> getServerConfigurationMap()
	{
		try {
			HashMap<Integer, String> map = new HashMap<Integer, String>();
			
			Statement st = DBConnection.getIstance().createStatement();
			ResultSet ris = st.executeQuery("SELECT * FROM " + DBTables.CONFIG);
			
			while(ris.next())
				map.put(ris.getInt("id"), ris.getString("value"));
			
			return map;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	public static HashMap<String, String> getProgramConfigurationMap(String programName)
	{
		try {
			HashMap<String, String> map = new HashMap<String, String>();
			
			String sql = "SELECT * FROM " + DBTables.PROGRAM + " WHERE name = ?";
			PreparedStatement st = DBConnection.getIstance().prepareStatement(sql);
			st.setString(1, programName);
			ResultSet ris = st.executeQuery();
			
			if(!ris.next()) return map;
			
			map.put(DBParameters.NAME, ris.getString("name"));
			map.put(DBParameters.EXTENZION, ris.getString("extenzion"));
			map.put(DBParameters.NEW_FILE, ris.getString("new_file"));
			
			return map;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public static boolean serverLogin(String userid, String password)
	{
		try {
			String sql;
			PreparedStatement ps;
			ResultSet ris;
			
			sql = "SELECT * FROM " + DBTables.CONFIG + " WHERE id=0 AND value=?";
			ps = DBConnection.getIstance().prepareStatement(sql);
			ps.setString(1, userid);
			ris = ps.executeQuery();
			
			if(!ris.next()) return false;
			
			sql = "SELECT * FROM " + DBTables.CONFIG + " WHERE id=1 AND value=?";
			ps = DBConnection.getIstance().prepareStatement(sql);
			ps.setString(1, password);
			
			ris = ps.executeQuery();
			
			return ris.next();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}
	
	public static boolean clientLogin(String userid, String password)
	{
		try {
			String sql = "SELECT * FROM " + DBTables.UTENTE + " WHERE userid=? AND password=?";
			PreparedStatement ps = DBConnection.getIstance().prepareStatement(sql);
			ps.setString(1, userid);
			ps.setString(2, password);
			
			ResultSet ris = ps.executeQuery();
						
			return ris.next();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}
	
	public static String returnStringFromSingleValueResultSet(ResultSet ris) throws SQLException
	{
		if(!ris.next()) return null;
		return ris.getString(1);
	}
	
	public static Integer returnIntFromSingleValueResultSet(ResultSet ris) throws SQLException
	{
		if(!ris.next()) return null;
		return ris.getInt(1);
	}
	
}
